<template>
  <div class="background">
    <div>
      <el-button type="primary" @click="addGroup">添加小组</el-button>
      <el-button type="success" @click="submitGroups">提交分组数据</el-button>
      <div v-for="(group, index) in groups" :key="index" class="group">
        <h3>小组 {{ index + 1 }}</h3>
        <el-transfer
          v-model="group.students"
          :data="students.filter(student => !isStudentInAnyGroup(student.key, groups, index))"
          filterable
          filter-placeholder="请输入关键词"
          :titles="['未分组学生', '小组成员']"
        ></el-transfer>
        <el-button type="text" @click="removeGroup(index)">删除小组</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElTransfer, ElButton, ElMessageBox } from 'element-plus';
import axios from 'axios';

// 定义学生数据
const students = ref([]);

// 定义小组数据
const groups = ref([]);

// 添加小组
const addGroup = async () => {
  try {
    // 如果当前小组数量已经达到上限（十个小组），则不执行添加操作
    if (groups.value.length >= 10) {
      console.log('已达到最大小组数量，无法继续添加。');
      return;
    }
    
    // 发送添加小组的请求到后台
    // const response = await axios.post('http://localhost:8080/groupss/add', {
    //   // groupId: groupId + 1,
    //   groupName: `小组 ${groups.value.length + 1}`,
    //   leaderId: 21201236,
    // });
    
    // 获取返回的小组ID
    const groupId = groups.value.length + 1;

    // 在前端添加小组
    groups.value.push({
      groupId: groupId,
      students: [],
    });
  } catch (error) {
    console.error('添加小组失败:', error);
  }
};

// 删除小组
const removeGroup = (index) => {
  ElMessageBox.confirm('确定要删除该小组吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    groups.value.splice(index, 1);
  }).catch(() => {
    // 取消删除操作
  });
};

// 提交分组数据
const submitGroups = async () => {
  try {
    // 构造需要提交的数据结构
    const groupMembers = [];
    groups.value.forEach((group, groupId) => {
      group.students.forEach(studentId => {
        groupMembers.push({
          memberId: studentId,
          groupId: groupId + 1, // 这里假设groupId从1开始，如果从0开始可以根据需求调整
        });
      });
    });

    console.log(groupMembers);

    // 发送数据到后端API进行处理
    const response = await axios.post('http://localhost:8080/group/addGroup02', groupMembers);
    console.log('提交成功:', response.data);

    // 更新每个小组的组长信息
    groups.value.forEach(async (group) => {
      if (group.students.length > 0) {
        try {
          await axios.post('http://localhost:8080/groupss/updateLeader', {
            groupId: group.groupId,
            leaderId: group.students[0], // 使用第一个成员作为组长
          });
        } catch (error) {
          console.error('更新组长信息失败:', error);
        }
      }
    });

  } catch (error) {
    console.error('提交失败:', error);
    // 可以添加错误处理逻辑，例如提示用户或记录日志
  }
};

// 判断学生是否在任何一个小组中
const isStudentInAnyGroup = (studentKey, groups, currentGroupIndex) => {
  for (let i = 0; i < groups.length; i++) {
    if (i !== currentGroupIndex && groups[i].students.includes(studentKey)) {
      return true;
    }
  }
  return false;
};

// 组件挂载时获取学生和分组信息
onMounted(async () => {
  try {
    // 获取学生信息
    const studentResponse = await axios.get('http://localhost:8080/student/getAll');
    const backendStudents = studentResponse.data;

    // 将后端数据映射成前端需要的格式并添加到前端状态中
    const formattedStudents = backendStudents.map(student => ({
      key: student.id,
      label: `${student.id} - ${student.name}`,
      name: student.name,
      account: student.account,
      password: student.password,
      gender: student.gender,
    }));

    // 更新前端的学生数据状态
    students.value = formattedStudents;

    // 获取分组信息
    const groupResponse = await axios.get('http://localhost:8080/group/getAll');
    const backendGroups = groupResponse.data;

    // 创建一个临时的分组对象
    const tempGroups = {};

   // 将分组数据按组分好
   backendGroups.forEach(groupMember => {
      const { groupId, memberId } = groupMember;
      if (!tempGroups[groupId]) {
        tempGroups[groupId] = {
          groupId: groupId, // 保存小组ID
          students: []
        };
      }
      tempGroups[groupId].students.push(memberId);
    });

    // 将分组数据映射成前端需要的格式并添加到前端状态中
    groups.value = Object.values(tempGroups);

  } catch (error) {
    console.error('获取数据失败:', error);
  }
});
</script>

<style>
.background {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5); /* Adjust the alpha (last parameter) for transparency */
  z-index: 999; /* Ensure it's above other content */
  display: flex;
  justify-content: center;
  align-items: center;
}

.background > div {
  background-color: white; /* Ensure the inner content area is opaque */
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.group {
  margin-bottom: 20px;
}
.background > div {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  overflow-y: auto; /* 添加滚动条 */
  max-height: 80vh; /* 限制最大高度为屏幕高度的80% */
}
</style>